//
//  ZYPaintView.m
//  Example
//
//  Created by wzp on 2024/8/17.
//

#import "ZYPaintView.h"
#import "IGraphDraw.h"
#import "ZYLine.h"
#import "ZYRect.h"
@interface ZYPaintView()
@property (nonatomic, strong) NSMutableArray <id<IGraphDraw>>*graphList;

@property (nonatomic, assign) CGPoint startPoint;
@end

@implementation ZYPaintView

- (instancetype)init
{
    if (self = [super init]) {
        self.graphList = [[NSMutableArray alloc] init];
    }
    return self;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    self.startPoint = [[touches anyObject] locationInView:self];
}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    CGPoint endPoint = [[touches anyObject] locationInView:self];
    
    if (self.startPoint.x > 0)
    {
        ZYLine *line = [[ZYLine alloc] initWithStartPoint:self.startPoint endPoint:endPoint];
        [self.graphList addObject:line];
    }
    else if (endPoint.x > 0) {
        ZYRect *rect = [[ZYRect alloc] initWithPoint:self.startPoint width:fabs(endPoint.x - self.startPoint.x) height:fabs(endPoint.y - self.startPoint.y)];
        [self.graphList addObject:rect];
    }
    
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect
{
    CGContextRef ref = UIGraphicsGetCurrentContext();
    for (int i = 0; i < self.graphList.count; i++) {
        id<IGraphDraw> graph = self.graphList[i];
        [graph drawInContextRef:ref color:[UIColor blackColor]];
    }
}

@end
